/*
 *    	@(#)@SystemResourceService4EasyUIImpl.java  2017年9月4日
 *     
 *      @COPYRIGHT@
 */
package com.capinfo.commons.project.service.security.impl;

import java.util.List;

import com.capinfo.commons.project.model.security.SystemResource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * <p>
 * 重写“buildResource”方法，用以实现可用于easyui tree的json。
 * </p>
 * 
 * @version 1.0
 * @author 张名扬
 */
public class SecurityResourceServiceImpl4EasyUI extends SecurityResourceServiceImpl {

	public String buildResourceJson() {

		SystemResource root = this.getResourceById((new SystemResource()).getRootId());

		JSONArray nodes = new JSONArray();
		JSONObject tree = new JSONObject();
		
		nodes.add(buildResource(tree, root));
		
		return nodes.toString();
	}
	
	private JSONObject buildResource(JSONObject tree, SystemResource root) {
		
		tree.put("id", root.getId());
		//tree.put("parentId", root.getParentId());
		tree.put("text", root.getName());

		JSONArray childrenNods = new JSONArray();
		
		List<SystemResource> children = root.getChildren();
		for(SystemResource child: children) {
			
			childrenNods.add(buildResource(new JSONObject(), child));
		}
		
		if( 0 != childrenNods.toArray().length ) {

			tree.put("children", childrenNods);
			
			if( !(new SystemResource()).getRootId().equals(root.getId()) ) {

				tree.put("state", "closed");
			}
		}
		
		return tree;
	}
}
